<?php
/**
 * Created by PhpStorm.
 * User: lelouchms
 * Date: 2019/3/28
 * Time: 20:20
 */

namespace app\common\util;


class TreeUtil
{


    public static function buildTree($data, $relationField, $parentField, $parentId)
    {
        $returnData = [];
        foreach ($data as $key => &$value) {
            if ($parentId === $value[$parentField]) {
                self::findChildren($value, $relationField, $parentField, $value[$relationField], $data);
                $returnData[] = $value;
            }
        }
        return $returnData;
    }

    public static function findChildren(&$data, $relationField, $parentField, $parentId, $source)
    {
        foreach ($source as $key => $value) {
            if ($value[$parentField] === $parentId) {
                $data['children'][] = $value;
            }
        }
        if (!empty($data['children'])) {
            foreach ($data['children'] as $key => $value) {
                self::findChildren($value, $relationField, $parentField, $value[$relationField], $source);
            }
        }
    }


}